/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shopping.model;

import org.apache.ibatis.session.SqlSession;
import shopping.commons.ModelObject;

import java.util.List;

/**
 * @author mazhao
 */
public class LoginInfo extends LoginInfoData {

    /** user is enabled */
    public static final int STATUS_ENABLE = 0;

    /** user is disabled */
    public static final int STATUS_DISABLE = 1;

    /** key for store in http session */
    public static final String SK_LOGIN_INFO = "shopping_customer_logininfo";

    /**
     * register user and connect role of user to him.
     * @return true for success, false else
     */
    public boolean register() {
        log.debug("begin login info register");
        super.beginTrans();
        try {
            super.save();
            String sqlKey = this.getClassName() + ".connectRole";
            session.insert(sqlKey, this.getUsername());
            super.commit();
            log.debug("login infor register success fully");
        } catch (Exception ex) {
            super.rollback();
            log.debug("login info register failed, with " + ex);
        }
        return true;
    }

    /**
     * List all users.
     * @return
     */
    public static List<LoginInfo> listAll() {

        String sqlKey = LoginInfo.class.getName() + ".listAll";

        SqlSession session = getSession();
        List<LoginInfo> users = session.selectList(sqlKey);

        return users;
    }

    public boolean enable() {
        String sqlKey = LoginInfo.class.getName() + ".enable";
        if(autoTrans) {
            session = getSession();
        }

        session.update(sqlKey, this);

        if(autoTrans) {
            session.commit();
            session.close();
        }
        return true;
    }

    public boolean disable() {
        String sqlKey = LoginInfo.class.getName() + ".disable";
        if(autoTrans) {
            session = getSession();
        }

        session.update(sqlKey, this);

        if(autoTrans) {
            session.commit();
            session.close();
        }
        return true;
    }

    public boolean changeRole() {
          String sqlKey = LoginInfo.class.getName() + ".changeRole";
        if(autoTrans) {
            session = getSession();
        }

        session.update(sqlKey, this);

        if(autoTrans) {
            session.commit();
            session.close();
        }
        return true;
    }
}
